package cn.chinaflame.pagodas.schedul;

import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.entity.PaBalmOrder;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.handle.HandlerException;
import cn.chinaflame.pagodas.repository.PaBalmOrderRepository;
import cn.chinaflame.pagodas.service.PaDonatrGoodsService;
import cn.chinaflame.pagodas.spring.ApplicationContextHolder;
import cn.chinaflame.pagodas.utils.ScheduleTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yw on 2018/10/16.
 */
public class PaBalmOrderFailure implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(PaBalmOrderFailure.class);

    private static Lock lock = new ReentrantLock();
    private PaBalmOrder paBalmOrder;

    public PaBalmOrderFailure (PaBalmOrder paBalmOrder) {
        this.paBalmOrder = paBalmOrder;
    }

    @Override
    public void run () {
        paBalmOrder = ApplicationContextHolder.getBean(PaBalmOrderRepository.class).findOne(paBalmOrder.getId());
        if (Sysconst.PAY_STATUS_SUC.equals(paBalmOrder.getPayStatus())) {
            log.info("订单已付款，不执行失效任务orderId:{},", paBalmOrder.getId());
        }else if (!Sysconst.PAY_STATUS_SUC.equals(paBalmOrder.getPayStatus())) {
            lock.lock();
            try {
                this.callBack(paBalmOrder);
            }catch (Exception e){
                log.error("异常信息", e);
                throw new HandlerException(CodeEnum.FAIL.getCode(), "系统异常", "系统异常", e);
            }finally {
                lock.unlock();
            }
        }
    }

    public static void callBack (PaBalmOrder paBalmOrder) {
        try {
            if (Sysconst.PAY_STATUS_WAIT.equals(paBalmOrder.getPayStatus())){
                paBalmOrder.setPayStatus(Sysconst.PAY_STATUS_PAY_TIMEOUT);
            }else if (Sysconst.PAY_STATUS_DOING.equals(paBalmOrder.getPayStatus())) {
                paBalmOrder.setPayStatus(Sysconst.PAY_STATUS_FAIL);
            }
            if ("2".equals(paBalmOrder.getOrderType())){
                ApplicationContextHolder.getBean(PaDonatrGoodsService.class).stock(paBalmOrder.getGoodsId(),1,"2");
            }
            ApplicationContextHolder.getBean(PaBalmOrderRepository.class).save(paBalmOrder);
        }catch (Exception e){
            log.error("异常信息", e);
            throw new HandlerException(CodeEnum.FAIL.getCode(), "系统异常", "系统异常", e);
        }finally {
            lock.unlock();
        }
    }


}
